// Created by Joe on 8/1/2017

app.controller(
    'HeatingStewardController',
    [
        'KEY', 'ins.helper', 'config', '$scope', '$location', '$timeout', 'UserService', 'HeatingStewardService',
        function (KEY, Helper, config, $scope, $location, $timeout, UserService, HeatingStewardService) {
            init();

            function init() {
                // set move
                $scope.position = config.HeatingSteward;

                // set page and panel
                $scope.page = ['home', 'mask'];
                $scope.limit = {list: 4};
                $scope.panel = {show: false, info: '', empty: false, load: false};

                // control
                $scope.control = {list: '', arrow: '', mf: false, keyboard: false};

                // current position
                $scope.cp = $scope.position[$scope.page[0]];

                // set focus
                $scope.focus = {ci: 'hs-h1'};

                // set input handler
                $scope.ele = '';

                // set cache
                $scope.cache = {history: config.cacheNS + '_heating'};
                $scope.history = {content: [], updateTime: ''};

                // add heating-steward logic
                addLogic();

                // set data
                $scope.data = {
                    area: config.curCity.cityName,
                    filter: '',
                    list: [],
                    curList: [],
                    curHistory: []
                };

                // get info
                $scope.panel.load = true;
                HeatingStewardService.getHeatingInfo($scope.data.area)
                    .then(function (info) {
                        info.forEach(function (item) {
                            $scope.data.list.push({
                                area: item['areaAdress'],
                                company: item['companyName'],
                                people: item['managerName'],
                                phone: item['managerPhone']
                            });
                        });

                        $scope.data.curList = $scope.data.list.slice(
                            $scope.control.list, $scope.control.list + $scope.limit.list
                        );
                        if ($scope.data.list.length > $scope.limit.list)
                            $scope.control.arrow = 'arrow-down--blur';

                        $scope.panel.load = false;
                        $scope.panel.empty = $scope.data.list.length === 0;
                    });

                // ele action
                $scope.move = function (evt, cb) {
                    evt.preventDefault();
                    // history current index
                    var ci = 0;
                    switch (evt.keyCode) {
                        case KEY.LEFT:
                            if (evt.target.id.indexOf('his') !== -1) {
                                ci = parseInt(evt.target.id.split('-')[1]);
                                $scope.focus.ci = 'his-' + (ci > 0 ? --ci : ci);
                            } else {
                                moveShim('left');
                            }
                            break;
                        case KEY.UP:
                            if (evt.target.id.indexOf('his') !== -1) {
                                $scope.focus.ci = 'hs-mk2';
                            } else {
                                moveShim('up');
                            }
                            break;
                        case KEY.RIGHT:
                            if (evt.target.id.indexOf('his') !== -1) {
                                ci = parseInt(evt.target.id.split('-')[1]);
                                $scope.focus.ci = 'his-' + (ci < $scope.data.curHistory.length - 1 ? ++ci : ci);
                            } else {
                                moveShim('right');
                            }
                            break;
                        case KEY.DOWN:
                            if (evt.target.id === 'hs-h1' && $scope.control.arrow) {
                                document.getElementById('hs-h1').blur();
                                $scope.control.arrow = 'arrow-down';
                            } else if (!((evt.target.id === 'hs-mk2' || evt.target.id === 'hs-mk3')
                                && $scope.data.curHistory.length === 0)) {
                                moveShim('down');
                            }
                            break;
                        case KEY.BACK:
                            // if ($scope.control.mf) {
                            //     if (evt.target.id === 'hs-mk1' && $scope.data.filter) {
                            //         $scope.data.filter = $scope.data.filter.substr(0, $scope.data.filter.length - 1);
                            //     }
                            // }
                            break;
                        case KEY.ENTER:
                            if (evt.target.id === 'hs-mk1') {
                                $scope.ele = evt.target;
                                $scope.ele.style.border = '2px solid #46a7e7';
                                $scope.ele.style.opacity = '1';
                                $('.scroll').css('top', -35);
                                inputFlag = true;
                                $scope.control.keyboard = true;
                                save_old_index();
                                change_components(0, 0, keyboardArray);
                                $timeout(function () {
                                    $("#keyboard_a").focus();
                                });
                            } else {
                                cb instanceof Function && cb();
                            }
                            break;
                    }
                };

                // global action
                document.addEventListener('keydown', globalAction);
            }

            function addLogic() {
                // open filter
                $scope.openFilter = function () {
                    if ($scope.panel.load) return;
                    dealHistory().get();
                    $scope.control.mf = true;
                    $scope.panel.empty = false;
                    $scope.cp = $scope.position['mask'];
                    resetFocus();
                };

                // close filter
                $scope.closeFilter = function (direct) {
                    return function () {
                        if (direct) $scope.panel.empty = $scope.data.list.length === 0;
                        $scope.control.mf = false;
                        $scope.cp = $scope.position['home'];
                        resetFocus();
                    };
                };

                // heating search
                $scope.heatingSearch = function () {
                    if ($scope.data.filter.length === 0) {
                        $scope.panel.info = '区域地址不能为空';
                        $scope.panel.show = true;
                        return;
                    }

                    $scope.data.area = $scope.data.filter;
                    $scope.data.list = [];
                    $scope.data.curList = [];
                    $scope.control.list = 0;
                    $scope.control.arrow = '';
                    $scope.panel.load = true;
                    $scope.panel.empty = false;
                    HeatingStewardService.getHeatingInfo($scope.data.area)
                        .then(function (info) {
                            // if (info.length === 0) {
                            //     $scope.panel.info = '暂无此区域信息';
                            //     $scope.panel.show = true;
                            //     return;
                            // }

                            info.forEach(function (item) {
                                $scope.data.list.push({
                                    area: item['areaAdress'],
                                    company: item['companyName'],
                                    people: item['managerName'],
                                    phone: item['managerPhone']
                                });
                            });

                            $scope.data.curList = $scope.data.list.slice(
                                $scope.control.list, $scope.control.list + $scope.limit.list
                            );
                            if ($scope.data.list.length > $scope.limit.list)
                                $scope.control.arrow = 'arrow-down--blur';

                            $scope.panel.load = false;
                            $scope.panel.empty = $scope.data.list.length === 0;
                            // record history only when info is not empty
                            info.length !== 0 && dealHistory().set();
                        });
                    $scope.closeFilter()();
                };

                // history search
                $scope.historySearch = function () {
                    $scope.data.list = [];
                    $scope.data.curList = [];
                    $scope.control.list = 0;
                    $scope.control.arrow = '';
                    $scope.panel.load = true;
                    $scope.panel.empty = false;
                    HeatingStewardService.getHeatingInfo(document.activeElement.innerText)
                        .then(function (info) {
                            info.forEach(function (item) {
                                $scope.data.list.push({
                                    area: item['areaAdress'],
                                    company: item['companyName'],
                                    people: item['managerName'],
                                    phone: item['managerPhone']
                                });
                            });

                            $scope.data.curList = $scope.data.list.slice(
                                $scope.control.list, $scope.control.list + $scope.limit.list
                            );
                            if ($scope.data.list.length > $scope.limit.list)
                                $scope.control.arrow = 'arrow-down--blur';

                            $scope.panel.empty = $scope.data.list.length === 0;
                            $scope.panel.load = false;
                            $scope.panel.empty = $scope.data.list.length === 0;
                        });
                    $scope.closeFilter()();
                };
            }

            function resetFocus(pos) {
                pos = pos || 0;
                $scope.focus.ci = $scope.cp[pos]['id'];
            }

            function dealHistory() {
                return {
                    get: function () {
                        Helper.opStorage($scope).get($scope.cache.history, 'history', true);
                        var len = $scope.history.content.length;
                        if (len > 0) $scope.data.curHistory = $scope.history.content.slice(0, len >= 4 ? 4 : len);
                    },
                    set: function () {
                        if ($scope.history.content.some(function (item) {
                                return item.name === $scope.data.filter;
                            })) return;

                        $scope.history.content.unshift({
                            name: $scope.data.area,
                            date: Date.now()
                        });
                        $scope.history.updateTime = Date.now();
                        Helper.opStorage().set($scope.cache.history, $scope.history);
                    }
                };
            }

            function globalAction() {
                event.preventDefault();
                var back = function () {
                    if ($scope.control.mf) return;
                    if (document.activeElement.id !== 'hs-h1') {
                        document.getElementById('hs-h1').focus();
                        $scope.control.list = 0;
                        $scope.data.curList = $scope.data.list.slice(
                            $scope.control.list, $scope.control.list + $scope.limit.list
                        );
                        $scope.control.arrow = 'arrow-down--blur';
                    } else {
                        $scope.$apply(function () {
                            $location.path('/home').replace();
                        });
                    }
                };
                var up = function () {
                    if ($scope.control.mf) return;
                    if ($scope.control.list > 0) {
                        $scope.data.curList = $scope.data.list.slice(
                            --$scope.control.list, $scope.control.list + $scope.limit.list
                        );
                        if ($scope.control.arrow !== 'arrow-down')
                            $scope.control.arrow = 'arrow-down';
                    } else {
                        document.getElementById('hs-h1').focus();
                        $scope.control.arrow = 'arrow-down--blur';
                    }
                };
                var down = function () {
                    if ($scope.control.mf) return;
                    if ($scope.control.list < $scope.data.list.length - $scope.limit.list) {
                        $scope.data.curList = $scope.data.list.slice(
                            ++$scope.control.list, $scope.control.list + $scope.limit.list
                        );
                        if ($scope.control.list + $scope.limit.list === $scope.data.list.length)
                            $scope.control.arrow = 'arrow-up';
                        else
                            $scope.control.arrow = 'arrow-down';
                    }
                };
                var enter = function () {
                    if ($scope.control.keyboard) {
                        if (inputFlag) {
                            if (inputLetter) {
                                inputLetter = false;
                                if ($scope.data.filter.length <= 14) {
                                    $scope.data.filter += charContainer;
                                }
                            }

                            if (document.activeElement.id === 'keyboard_dele') {
                                if ((isChinese && chineseSearch < 0)
                                    || (!isChinese && $scope.data.filter.length > 0)) {
                                    $scope.data.filter = $scope.data.filter.substr(0, $scope.data.filter.length - 1);
                                }
                            }
                        } else {
                            $('.scroll').css('top', 0);
                            $scope.ele.style.border = '2px solid rgba(255, 255, 255, .1)';
                            $scope.ele.focus();
                            $scope.control.keyboard = false;
                        }
                    }
                };

                switch (event.keyCode) {
                    case KEY.UP:
                        up();
                        break;
                    case KEY.DOWN:
                        down();
                        break;
                    case KEY.BACK:
                        back();
                        break;
                    case KEY.ENTER:
                        enter();
                        break;
                }

                $scope.$digest();
            }

            function moveShim(dir) {
                var curFocus = $scope.cp.filter(function (item) {
                    return item.id === $scope.focus.ci;
                })[0];
                if (curFocus['move'][dir] !== -1) {
                    $scope.focus.ci = curFocus['move'][dir];
                }
            }

            $scope.$on('$destroy', function () {
                document.removeEventListener('keydown', globalAction);
            });
        }
    ]
);